package com.hongtech.common.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hongtech.common.bean.Token;

/**
 * Token操作工具类
 */
public class TokenUtil {

	/**
	 * 存储Token信息到Session
	 *
	 * @param token token信息
	 * @param request 请求实体
	 */
	public static void addToken(Token token, HttpServletRequest request) {
		request.getSession().setAttribute("token", token);
	}

	/**
	 * 清理Token
	 *
	 * @param request 请求对象
	 */
	public static void clearLogin(HttpServletRequest request) {
		request.getSession().removeAttribute("token");
	}

	/**
	 * 清理Token并重定向到登录页面
	 *
	 * @param request 请求实体
	 * @param response 响应实体
	 */
	public static void clearRedirectLogin(HttpServletRequest request, HttpServletResponse response) {
		try {
			clearLogin(request);
			String contextPath = request.getContextPath();
			response.sendRedirect(contextPath + "/login");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取Token
	 *
	 * @param request 请求对象
	 * @return 返回token信息
	 */
	public static Token getToken(HttpServletRequest request) {
		Object object = request.getSession().getAttribute("token");
		if (object == null) {
			return null;
		}
		return (Token) object;
	}

}
